package com.yidian.controller;

import com.yidian.common.entity.Result;
import com.yidian.common.utils.RedisUtils;
import com.yidian.dto.LoginDto;
import com.yidian.entity.User;
import com.yidian.entity.UserExample;
import com.yidian.service.impl.UserServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

//@Controller
//@ResponseBody

@RestController
@RequestMapping("/login")
@Api(value = "/login", tags = "登录注册接口")
public class LoginController {
    @Autowired
    private UserServiceImpl userService;

    /**
     * 发送登录验证码
     *
     * @param telephone
     * @return
     */
    @GetMapping("/sms/codes/{mobile}")
    @ApiOperation(value = "发送短信验证码", notes = "发送短信验证码方法", httpMethod = "GET", response = Result.class)
    public Result SendSms(@PathVariable("mobile") String telephone) {

        //随机生成验证码
        String authCode = RandomStringUtils.randomNumeric(6);
        System.out.println("给手机：" + telephone + " 发送登录验证码：" + authCode);
        //发送短信验证码
        return userService.sendSms(telephone, authCode);
    }


    /**
     * 进行登录、注册
     * @param loginDto
     * @param session
     * @return
     */
    @PostMapping("/doLogin")
    @ApiOperation(value = "进行登录、注册", notes = "进行登录、注册", httpMethod = "POST", response = Result.class)
    public Result login(@RequestBody LoginDto loginDto, HttpSession session) {

        List<User> user = userService.selectByExample(loginDto);

        //如果用户对象为空，则进行用户注册
        if (user == null || user.size() != 1) {
            return userService.register(loginDto);
        }
        //如果用户不为空，进行登录
        else {
            return userService.login(loginDto, user.get(0));
        }
    }


}
